import os
import shutil

from magika import Magika
from pathlib import Path


def test():
    basepath = r'D:\官华林U盘\chk'
    outpath = r'D:\官华林U盘\res'
    # 搜索文件
    # os.listdir(basepath)
    m = Magika()
    for root, dirs, files in os.walk(basepath):
        for file in files:
            # 使用谷歌AI引擎分析文件结构
            # m = Magika()
            filepath = os.path.join(root, file)
            res = m.identify_path(Path(filepath))
            fileexname = res.output.ct_label  # 扩展名
            print(filepath, fileexname)

            # 创建目录
            tpath = os.path.join(outpath, fileexname)
            if not os.path.exists(tpath):
                try:
                    os.makedirs(tpath)
                    pass
                except FileExistsError:
                    print("该目录已存在")
                except Exception as e:
                    print("创建目录时发生错误:", str(e))
            tagfile = os.path.join(tpath, file) + '.' + fileexname
            shutil.copyfile(filepath, tagfile)
        # print(os.path.join(root, file))

    # res = m.identify_path(Path(r'D:\官华林U盘\chk\FOUND.000\FILE0223.CHK'))
    # res = m.identify_bytes(b"{https://github.com/google/magika}")

    pass


if __name__ == '__main__':
    test()
